package com.hyp.pay.UI.Home.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.tts.auth.AuthInfo;
import com.baidu.tts.client.SpeechError;
import com.baidu.tts.client.SpeechSynthesizeBag;
import com.baidu.tts.client.SpeechSynthesizer;
import com.baidu.tts.client.SpeechSynthesizerListener;
import com.baidu.tts.client.TtsMode;
import com.hyp.pay.R;
import com.hyp.pay.UI.Home.presenter.Edit2Presenter;
import com.hyp.pay.UI.Home.presenter.EditPresenter;
import com.hyp.pay.UI.Home.presenter.contract.Edit2Contract;
import com.hyp.pay.UI.Home.presenter.contract.EditContract;
import com.hyp.pay.UI.Zxing.activity.TestScanActivity;
import com.hyp.pay.base.BaseActivity;
import com.hyp.pay.base.SimpleActivity;
import com.hyp.pay.device.N900Device;
import com.hyp.pay.http.Constants;
import com.hyp.pay.http.HyqApis;
import com.hyp.pay.model.FindRecharge;
import com.hyp.pay.model.UserJson;
import com.hyp.pay.utils.LinePathView;
import com.hyp.pay.utils.SPUtil;
import com.hyp.pay.weight.ProgressDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;

public class EditActivity extends BaseActivity<EditPresenter> implements View.OnClickListener, EditContract.View, SpeechSynthesizerListener {

    private static N900Device n900Device;

    //   百度
    private SpeechSynthesizer mSpeechSynthesizer;
    private String mSampleDirPath;
    private static final String SAMPLE_DIR_NAME = "baiduTTS";
    private static final String SPEECH_FEMALE_MODEL_NAME = "bd_etts_speech_female.dat";
    private static final String SPEECH_MALE_MODEL_NAME = "bd_etts_speech_male.dat";
    private static final String TEXT_MODEL_NAME = "bd_etts_text.dat";
    private static final String LICENSE_FILE_NAME = "temp_license";
    private static final String ENGLISH_SPEECH_FEMALE_MODEL_NAME = "bd_etts_speech_female_en.dat";
    private static final String ENGLISH_SPEECH_MALE_MODEL_NAME = "bd_etts_speech_male_en.dat";
    private static final String ENGLISH_TEXT_MODEL_NAME = "bd_etts_text_en.dat";

    private static final int PRINT = 0;
    private static final int UI_CHANGE_INPUT_TEXT_SELECTION = 1;
    private static final int UI_CHANGE_SYNTHES_TEXT_SELECTION = 2;

    private  String username;
    private Bitmap mBitmap;


    TextView mClean;
    LinePathView pathView;
    Button mSureQian;
    TextView data;
    String id;

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);

    }

    @Override
    protected int getLayout() {
        return R.layout.activity_edit;
    }



    @Override
    protected void initView() {
        mClean = (TextView) findViewById(R.id.clean);
        pathView = (LinePathView) findViewById(R.id.view);
        mSureQian = (Button) findViewById(R.id.sure_qian);
        data = (TextView) findViewById(R.id.time);
        mClean.setOnClickListener(this);
        mSureQian.setOnClickListener(this);


        mPresenter.getUsr(SPUtil.getUserid());
        pathView.setBackColor(getResources().getColor(R.color.c_f1f1f1));



        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日    HH:mm:ss     ");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        data.setText(str);
        createChineseQRCode(SPUtil.getID());
        initialEnv();
        initialTts();
    }

    private void createChineseQRCode(final String id) {
        /*
        这里为了偷懒，就没有处理匿名 AsyncTask 内部类导致 Activity 泄漏的问题
        请开发在使用时自行处理匿名内部类导致Activity内存泄漏的问题，处理方式可参考 https://github.com/GeniusVJR/LearningNotes/blob/master/Part1/Android/Android%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F%E6%80%BB%E7%BB%93.md
         */

//    http://pay.maicool.cn/hyqPayService/
        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                return QRCodeEncoder.syncEncodeQRCode("http://pay.maicool.cn/hyqPayService//app_countLogDetail2.html?countLogId="+id+"&userId="+SPUtil.getUserid(), BGAQRCodeUtil.dp2px(mContext, 150));
            }

            @Override
            protected void onPostExecute(Bitmap bitmap2) {
                if (bitmap2 != null) {
                    mBitmap=bitmap2;
                    Log.i("olj",mBitmap.toString());
                } else {
                }
            }
        }.execute();
    }
    // 初始化设备
    public void connectDevice2() {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    n900Device.connectDevice();
                }
            }).start();
        } catch (Exception e) {
//            showMessage("设备连接异常：" + e, Const.MessageTag.ERROR);
        }

    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.clean:
                pathView.setPenColor(Color.BLACK);
                pathView.setBackColor(getResources().getColor(R.color.c_f1f1f1));
                pathView.clear();
                break;
            case R.id.sure_qian:
                if (pathView.getTouched()) {
                    // 获取内置SD卡路径
                    String sdCardPath = Environment.getExternalStorageDirectory().getPath();
                    // 图片文件路径
                    String filePath = sdCardPath + File.separator + "screenshot2.png";
                    File file = new File(filePath);
                    Log.d("olj", file.length() + "");
                    try {
                        pathView.save(filePath);
                        SPUtil.setSignDraweeName(filePath);
                        Log.i("olj", "收款人签名" + filePath);
                        Toast.makeText(this, "签名保存成功", Toast.LENGTH_SHORT).show();
                        mSureQian.setEnabled(false);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    screenshot();
                } else {
                    Toast.makeText(this, "请签名", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void screenshot() {
        // 获取屏幕
        View dView = getWindow().getDecorView();
        dView.setDrawingCacheEnabled(true);
        dView.buildDrawingCache();
        Bitmap bmp = dView.getDrawingCache();
        if (bmp != null) {
            try {
                // 获取内置SD卡路径
                String sdCardPath = Environment.getExternalStorageDirectory().getPath();
                // 图片文件路径
                String filePath = sdCardPath + File.separator + "short2.png";

                File file = new File(filePath);
                FileOutputStream fos = new FileOutputStream(file);
//                bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
//                os.flush();
//                os.close();
                if (null != fos) {
                    boolean success = bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
                    fos.flush();
                    fos.close();
                    if (success)
                    SPUtil.setSignDraweeDiv(filePath);
                    Log.i("olj", "收款人截屏" + filePath);
                    Toast.makeText(this, "截屏成功", Toast.LENGTH_SHORT).show();

                    Log.i("olj", SPUtil.getSignFace());
                    Log.i("olj", SPUtil.getSignDraweeDiv());
                    Log.i("olj", SPUtil.getSignPayerDiv());
                    Log.i("olj", SPUtil.getSignDraweeName());
                    Log.i("olj", SPUtil.getSignPayervName());
                    Log.i("olj", SPUtil.getUserid());
                    Log.i("olj", SPUtil.getOrder());

                    mPresenter.getUploadFileIDCard(SPUtil.getSignFace(), SPUtil.getSignDraweeDiv(), SPUtil.getSignPayerDiv(),
                            SPUtil.getSignDraweeName(), SPUtil.getSignPayervName(),
                            Integer.parseInt(SPUtil.getUserid()), SPUtil.getOrder());
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    @Override
    public void showUplod(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            Log.i("olj", data);
            String code = jsonObject.getString("code");
            String msg = jsonObject.getString("msg");
            Log.i("olj", code);
            if (code.equals("200")) {

                Log.i("olj",SPUtil.getOrder());

                mPresenter.getFindRecharge(SPUtil.getOrder());

//                createChineseQRCode(SPUtil.getID());
//                speak();
//                Intent intent = new Intent(mContext, WebViewActivity.class);
//                intent.putExtra(Constants.WEB_VIEW_URL_PATH, HyqApis.HOST + "app_systemSuccess.html");
//                startActivity(intent);
//                finish();
//                Toast.makeText(mContext,msg, Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showFindRecharge(FindRecharge charge) throws JSONException {
        if (charge.getCode().equals("200")){

            String paymentId=charge.getHyqAccountRecharge().getPaymentId();
            String paymentTime=charge.getHyqAccountRecharge().getPaymentTime();
            String moneyFloat=charge.getHyqAccountRecharge().getMoneyfloat();
            String logno=charge.getHyqAccountRecharge().getLogno();
            String shopTradeNo=charge.getHyqAccountRecharge().getShopTradeNo();
            id=charge.getHyqAccountRecharge().getId();
            SPUtil.seId(id);
            int payMode=charge.getHyqAccountRecharge().getPayMode();
            int paymentStatus=charge.getHyqAccountRecharge().getPaymentStatus();

            String text;
            String pay = "微信";

            if (paymentStatus==0){
                text="待支付";
            }else if (paymentStatus==1){
                text="已支付";
            }else if (paymentStatus==2){
                text="支付失败";
            }else{
                text="异常";
            }

            if (payMode==1){
                pay="微信";
            }else if(payMode==2){
                pay="支付宝";
            }else if (payMode==3){
                pay="百度钱包";
            }else if (payMode==4){
                pay="QQ钱包";
            }else if(payMode==5){
                pay="京东钱包";
            }

            String signImglist=charge.getHyqAccountRecharge().getSignImglist();
            JSONObject jsonObject = new JSONObject(signImglist);
            String  SignPayerName=jsonObject.getString("SignPayerName");
            String  SignDraweeName=jsonObject.getString("SignDraweeName");

            SPUtil.setPaymode(pay);
            SPUtil.setPaymentId(paymentId);
            SPUtil.setSignPayerName(SignPayerName);
            SPUtil.setPaymentTime(paymentTime);
            SPUtil.setText(text);
            SPUtil.setMoneyFloat(moneyFloat);
            SPUtil.setLogno(logno);
            SPUtil.setShopTradeNo(shopTradeNo);
            SPUtil.setDraweeName(SignDraweeName);



            speak();

//              新大陆pos机打印
            if (android.os.Build.DISPLAY.equals("NewLand_N900-7cfaf9357f")) {
                n900Device = N900Device.getInstance(this,paymentId,paymentTime,moneyFloat,text,pay,SignPayerName,username,mBitmap);
                connectDevice2();
            }
//            衫德pos机打印
//            获取序列号：
//            String serialNum = android.os.Build.SERIAL;
//            if (serialNum)
            Intent intent = new Intent(mContext, WebViewActivity.class);
            intent.putExtra(Constants.WEB_VIEW_URL_PATH, HyqApis.HOST + "app_systemSuccess.html");
            startActivity(intent);
            finish();

        }

    }

    @Override
    public void showUser(UserJson data) {
        if (data.getCode().equals("200")){

            username= data.getHyqUser().getUsername();

            SPUtil.setUsername(username);


        }

    }

    @Override
    public void showError(String msg) {

    }


    private void initialEnv() {
        if (mSampleDirPath == null) {
            String sdcardPath = Environment.getExternalStorageDirectory().toString();
            mSampleDirPath = sdcardPath + "/" + SAMPLE_DIR_NAME;
        }
        makeDir(mSampleDirPath);
        copyFromAssetsToSdcard(false, SPEECH_FEMALE_MODEL_NAME, mSampleDirPath + "/" + SPEECH_FEMALE_MODEL_NAME);
        copyFromAssetsToSdcard(false, SPEECH_MALE_MODEL_NAME, mSampleDirPath + "/" + SPEECH_MALE_MODEL_NAME);
        copyFromAssetsToSdcard(false, TEXT_MODEL_NAME, mSampleDirPath + "/" + TEXT_MODEL_NAME);
        copyFromAssetsToSdcard(false, LICENSE_FILE_NAME, mSampleDirPath + "/" + LICENSE_FILE_NAME);
        copyFromAssetsToSdcard(false, "english/" + ENGLISH_SPEECH_FEMALE_MODEL_NAME, mSampleDirPath + "/"
                + ENGLISH_SPEECH_FEMALE_MODEL_NAME);
        copyFromAssetsToSdcard(false, "english/" + ENGLISH_SPEECH_MALE_MODEL_NAME, mSampleDirPath + "/"
                + ENGLISH_SPEECH_MALE_MODEL_NAME);
        copyFromAssetsToSdcard(false, "english/" + ENGLISH_TEXT_MODEL_NAME, mSampleDirPath + "/"
                + ENGLISH_TEXT_MODEL_NAME);
    }

    private void makeDir(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 将sample工程需要的资源文件拷贝到SD卡中使用（授权文件为临时授权文件，请注册正式授权）
     *
     * @param isCover 是否覆盖已存在的目标文件
     * @param source
     * @param dest
     */
    private void copyFromAssetsToSdcard(boolean isCover, String source, String dest) {
        File file = new File(dest);
        if (isCover || (!isCover && !file.exists())) {
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = getResources().getAssets().open(source);
                String path = dest;
                fos = new FileOutputStream(path);
                byte[] buffer = new byte[1024];
                int size = 0;
                while ((size = is.read(buffer, 0, 1024)) >= 0) {
                    fos.write(buffer, 0, size);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initialTts() {
        this.mSpeechSynthesizer = SpeechSynthesizer.getInstance();
        this.mSpeechSynthesizer.setContext(this);
        this.mSpeechSynthesizer.setSpeechSynthesizerListener(this);
        // 文本模型文件路径 (离线引擎使用)
        this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_TEXT_MODEL_FILE, mSampleDirPath + "/"
                + TEXT_MODEL_NAME);
        // 声学模型文件路径 (离线引擎使用)
        this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_SPEECH_MODEL_FILE, mSampleDirPath + "/"
                + SPEECH_FEMALE_MODEL_NAME);
        // 本地授权文件路径,如未设置将使用默认路径.设置临时授权文件路径，LICENCE_FILE_NAME请替换成临时授权文件的实际路径，仅在使用临时license文件时需要进行设置，如果在[应用管理]中开通了正式离线授权，不需要设置该参数，建议将该行代码删除（离线引擎）
        // 如果合成结果出现临时授权文件将要到期的提示，说明使用了临时授权文件，请删除临时授权即可。
        this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_LICENCE_FILE, mSampleDirPath + "/"
                + LICENSE_FILE_NAME);
//        // 请替换为语音开发者平台上注册应用得到的App ID (离线授权)
//        this.mSpeechSynthesizer.setAppId("9751744"/*这里只是为了让Demo运行使用的APPID,请替换成自己的id。*/);
//        // 请替换为语音开发者平台注册应用得到的apikey和secretkey (在线授权)
//        this.mSpeechSynthesizer.setApiKey("Vq7tQk64Blvxx1ZfEyH25PtI",
//                "IfL68I092GYC3FGAgvtQisqERmZMGqXl"/*这里只是为了让Demo正常运行使用APIKey,请替换成自己的APIKey*/);

        // 请替换为语音开发者平台上注册应用得到的App ID (离线授权)
        this.mSpeechSynthesizer.setAppId("8535996"/*这里只是为了让Demo运行使用的APPID,请替换成自己的id。*/);
        // 请替换为语音开发者平台注册应用得到的apikey和secretkey (在线授权)
        this.mSpeechSynthesizer.setApiKey("MxPpf3nF5QX0pndKKhS7IXcB",
                "7226e84664474aa098296da5eb2aa434"/*这里只是为了让Demo正常运行使用APIKey,请替换成自己的APIKey*/);
        // 发音人（在线引擎），可用参数为0,1,2,3。。。（服务器端会动态增加，各值含义参考文档，以文档说明为准。0--普通女声，1--普通男声，2--特别男声，3--情感男声。。。）
        this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEAKER, "0");
        // 设置Mix模式的合成策略
        this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_MIX_MODE, SpeechSynthesizer.MIX_MODE_DEFAULT);
        // 授权检测接口(只是通过AuthInfo进行检验授权是否成功。)
        // AuthInfo接口用于测试开发者是否成功申请了在线或者离线授权，如果测试授权成功了，可以删除AuthInfo部分的代码（该接口首次验证时比较耗时），不会影响正常使用（合成使用时SDK内部会自动验证授权）
        AuthInfo authInfo = this.mSpeechSynthesizer.auth(TtsMode.MIX);

        if (authInfo.isSuccess()) {
//            toPrint("auth success");
        } else {
            String errorMsg = authInfo.getTtsError().getDetailMessage();
//            toPrint("auth failed errorMsg=" + errorMsg);
        }

        // 初始化tts
        mSpeechSynthesizer.initTts(TtsMode.MIX);

    }


    private void speak() {

        int result = this.mSpeechSynthesizer.speak("您已收款" + SPUtil.getCharge() + "元");

        if (result < 0) {
            toPrint("error,please look up error code in doc or URL:http://yuyin.baidu.com/docs/tts/122 ");
        }
    }


    private SpeechSynthesizeBag getSpeechSynthesizeBag(String text, String utteranceId) {
        SpeechSynthesizeBag speechSynthesizeBag = new SpeechSynthesizeBag();
        //需要合成的文本text的长度不能超过1024个GBK字节。
        speechSynthesizeBag.setText(text);
        speechSynthesizeBag.setUtteranceId(utteranceId);
        return speechSynthesizeBag;
    }

    /*
     * @param arg0
     */
    @Override
    public void onSynthesizeStart(String utteranceId) {
//        toPrint("onSynthesizeStart utteranceId=" + utteranceId);
    }

    /**
     * 合成数据和进度的回调接口，分多次回调
     *
     * @param utteranceId
     * @param data        合成的音频数据。该音频数据是采样率为16K，2字节精度，单声道的pcm数据。
     * @param progress    文本按字符划分的进度，比如:你好啊 进度是0-3
     */
    @Override
    public void onSynthesizeDataArrived(String utteranceId, byte[] data, int progress) {
        // toPrint("onSynthesizeDataArrived");
        mHandler.sendMessage(mHandler.obtainMessage(UI_CHANGE_SYNTHES_TEXT_SELECTION, progress, 0));
    }

    /**
     * 合成正常结束，每句合成正常结束都会回调，如果过程中出错，则回调onError，不再回调此接口
     *
     * @param utteranceId
     */
    @Override
    public void onSynthesizeFinish(String utteranceId) {
//        toPrint("onSynthesizeFinish utteranceId=" + utteranceId);
    }

    /**
     * 播放开始，每句播放开始都会回调
     *
     * @param utteranceId
     */
    @Override
    public void onSpeechStart(String utteranceId) {
//        toPrint("onSpeechStart utteranceId=" + utteranceId);
    }

    /**
     * 播放进度回调接口，分多次回调
     *
     * @param utteranceId
     * @param progress    文本按字符划分的进度，比如:你好啊 进度是0-3
     */
    @Override
    public void onSpeechProgressChanged(String utteranceId, int progress) {
        // toPrint("onSpeechProgressChanged");
        mHandler.sendMessage(mHandler.obtainMessage(UI_CHANGE_INPUT_TEXT_SELECTION, progress, 0));
    }

    /**
     * 播放正常结束，每句播放正常结束都会回调，如果过程中出错，则回调onError,不再回调此接口
     *
     * @param utteranceId
     */
    @Override
    public void onSpeechFinish(String utteranceId) {
//        toPrint("onSpeechFinish utteranceId=" + utteranceId);
    }

    /**
     * 当合成或者播放过程中出错时回调此接口
     *
     * @param utteranceId
     * @param error       包含错误码和错误信息
     */
    @Override
    public void onError(String utteranceId, SpeechError error) {
        toPrint("onError error=" + "(" + error.code + ")" + error.description + "--utteranceId=" + utteranceId);
    }

    private Handler mHandler = new Handler() {

        /*
         * @param msg
         */
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            switch (what) {
                case PRINT:
                    print(msg);
                    break;
//
                default:
                    break;
            }
        }

    };

    private void toPrint(String str) {
        Message msg = Message.obtain();
        msg.obj = str;
        this.mHandler.sendMessage(msg);
    }

    private void print(Message msg) {
        String message = (String) msg.obj;
        if (message != null) {
            Log.w("olkj", message);
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        }
    }

}
